package com.atguigu.test;

/**
 * 冒泡排序
 */
public class BubbleSort {
    public static void bubbleSort(int[] array) {
        int n = array.length;
        boolean swapped;
        //外层循环控制遍历次数
        for (int i = 0; i < n - 1; i++) {
            swapped = false;
            //内层循环进行两两比较和交换
            for (int j = 0; j < n - 1 - i; j++) {
                if (array[j] > array[j + 1]) {
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                    swapped = true;
                }
            }
            //如果没有发生交换，数组已经有序，提前退出
            if (!swapped) {
                break;
            }
        }
    }

    public static void main(String[] args) {
        int[] array = {64, 34, 25, 12, 22, 11, 90};
        System.out.println("排序前的数组：");
        for (int num : array) {
            System.out.print(num + " ");
        }
        bubbleSort(array);
        System.out.println("\n排序后的数组：");
        for (int num : array) {
            System.out.print(num + " ");
        }
    }

}
